<template>
  <section class="login-page">
    <div class="login-card">
      <div v-if="!isAuthenticated">
        <div class="auth-toggle">
          <button 
            class="toggle-button" 
            :class="{ active: !isRegister }"
            @click="isRegister = false"
          >
            登录
          </button>
          <button 
            class="toggle-button" 
            :class="{ active: isRegister }"
            @click="isRegister = true"
          >
            注册
          </button>
        </div>

        <h1 class="login-title">{{ isRegister ? '创建账号' : '登录' }}</h1>
        <p class="login-subtitle">{{ isRegister ? '创建新账号开始使用' : '使用你的账号进入知识库' }}</p>
        
        <form class="login-form" @submit.prevent="onSubmit">
          <div v-if="isRegister" class="form-item">
            <label>昵称</label>
            <input v-model="name" type="text" required />
          </div>
          <div class="form-item">
            <label>用户名</label>
            <input v-model="username" required />
          </div>
          <div class="form-item">
            <label>密码</label>
            <input v-model="password" type="password" required :minlength="6" />
          </div>
          <div v-if="isRegister" class="form-item">
            <label>确认密码</label>
            <input v-model="confirmPassword" type="password" required :minlength="6" />
          </div>
          
          <button class="login-button" type="submit" :disabled="loading">
            {{ loading ? (isRegister ? '注册中...' : '登录中...') : (isRegister ? '注册' : '登录') }}
          </button>
        </form>
        
        <p v-if="error" class="login-error">{{ error }}</p>
        
        <div class="auth-switch">
          {{ isRegister ? '已有账号？' : '还没有账号？' }}
          <a href="#" @click.prevent="isRegister = !isRegister">
            {{ isRegister ? '去登录' : '立即注册' }}
          </a>
        </div>
      </div>

      <!-- 已登录状态 -->
      <div v-else class="user-info">
        <div class="user-avatar">
          {{ user.name ? user.name.charAt(0).toUpperCase() : 'U' }}
        </div>
        <h2 class="welcome-text">欢迎回来, {{ user.name || user.username }}</h2>
        <p class="user-email">{{ user.username }}</p>
        
        <div class="action-buttons">
          <button @click="goToDashboard" class="action-button primary">
            进入控制台
          </button>
          <button @click="handleLogout" class="action-button secondary">
            退出登录
          </button>
        </div>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';

const username = ref('');
const password = ref('');
const name = ref('');
const confirmPassword = ref('');
const isRegister = ref(false);
const loading = ref(false);
const error = ref('');
const router = useRouter();

// 使用身份验证状态
const { user, isAuthenticated, logout: authLogout, initAuth, refreshAuth } = useAuth();

// 初始化身份信息，已登录时展示欢迎卡片
onMounted(async () => {
  await initAuth();
});

// 退出登录
const handleLogout = async () => {
  try {
    await authLogout();
  } catch (e) {
    console.error('Logout error:', e);
  }
};

// 跳转到控制台
const goToDashboard = () => {
  router.push('/');
};

const validateForm = () => {
  if (isRegister.value) {
    if (password.value !== confirmPassword.value) {
      error.value = '两次输入的密码不一致';
      return false;
    }
    if (password.value.length < 6) {
      error.value = '密码长度不能少于6位';
      return false;
    }
  }
  return true;
};

const resetForm = () => {
  if (!isRegister.value) {
    name.value = '';
    confirmPassword.value = '';
  }
  error.value = '';
};

async function handleLogin() {
  try {
    const res = await fetch('/api/auth/login', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ 
        username: username.value, 
        password: password.value 
      }),
      credentials: 'include' // 确保发送和接收 cookies
    });

    const data = await res.json();
    
    if (!res.ok) {
      throw new Error(data.error || '登录失败');
    }

    // 更新 useAuth 中的用户状态
    if (data.user) {
      await refreshAuth();
      // 如果用户直接访问登录页面，跳转到首页
      router.push('/');
    } else {
      throw new Error('登录信息不完整');
    }
  } catch (e) {
    console.error('Login error:', e);
    throw e;
  }
}

async function handleRegister() {
  try {
    const res = await fetch('/api/auth/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name: name.value,
        username: username.value,
        password: password.value
      }),
    });

    const data = await res.json();
    
    if (!res.ok) {
      throw new Error(data.statusMessage || '注册失败');
    }

    // 注册成功后自动登录
    await handleLogin();
  } catch (e) {
    console.error('Registration error:', e);
    throw new Error(e.message || '注册失败，请稍后重试');
  }
}

async function onSubmit() {
  if (!validateForm()) return;
  
  loading.value = true;
  error.value = '';
  
  try {
    if (isRegister.value) {
      await handleRegister();
    } else {
      await handleLogin();
    }
  } catch (e) {
    error.value = e.message || (isRegister.value ? '注册失败' : '登录失败');
  } finally {
    loading.value = false;
  }
}

// 切换登录/注册时重置表单
watch(isRegister, () => {
  resetForm();
});
</script>

<style scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-bottom: 0.5rem;
}

.login-card {
  width: min(520px, 92vw);
  background: #fff;
  border-radius: 1rem;
  padding: 2.5rem;
  box-shadow: 0 24px 60px rgba(15, 23, 42, 0.12);
}

.toggle-button {
  flex: 1;
  padding: 0.5rem;
  border: none;
  background: none;
  font-size: 1rem;
  font-weight: 500;
  color: #64748b;
  cursor: pointer;
  transition: all 0.2s;
  position: relative;
}

.toggle-button.active {
  color: #3b82f6;
  font-weight: 600;
}

.toggle-button.active::after {
  content: '';
  position: absolute;
  bottom: -0.5rem;
  left: 0;
  right: 0;
  height: 2px;
  background-color: #3b82f6;
}

.login-title {
  font-size: 1.5rem;
  font-weight: 700;
  color: #1e293b;
  margin-bottom: 0.5rem;
}

.login-subtitle {
  font-size: 0.875rem;
  color: #64748b;
  margin-bottom: 1.5rem;
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.form-item label {
  font-size: 0.875rem;
  font-weight: 500;
  color: #334155;
}

.form-item input {
  width: 100%;
  padding: 0.625rem 0.875rem;
  border: 1px solid #e2e8f0;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  transition: border-color 0.2s, box-shadow 0.2s;
  box-sizing: border-box;
}

.form-item input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.login-button {
  margin-top: 0.5rem;
  padding: 0.625rem 1rem;
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 0.375rem;
  font-size: 0.9375rem;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.login-button:hover {
  background-color: #2563eb;
}

.login-button:disabled {
  background-color: #bfdbfe;
  cursor: not-allowed;
}

.login-error {
  color: #ef4444;
  font-size: 0.875rem;
  margin-top: 1rem;
  text-align: center;
}

.auth-switch {
  text-align: center;
  font-size: 0.875rem;
  color: #64748b;
  margin-top: 1.5rem;
}

a {
  color: #3b82f6;
  text-decoration: none;
  font-weight: 500;
}

a:hover {
  text-decoration: underline;
}

/* 用户信息样式 */
.user-info {
  text-align: center;
  padding: 1.5rem 0;
}

.user-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 1.5rem;
  border-radius: 50%;
  background-color: #3b82f6;
  color: white;
  font-size: 2rem;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
}

.welcome-text {
  font-size: 1.5rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
  color: #1e293b;
}

.user-email {
  color: #64748b;
  margin-bottom: 2rem;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  margin-top: 2rem;
}

.action-button {
  padding: 0.75rem 1.5rem;
  border-radius: 0.5rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  border: none;
  font-size: 1rem;
}

.action-button.primary {
  background-color: #3b82f6;
  color: white;
}

.action-button.primary:hover {
  background-color: #2563eb;
}

.action-button.secondary {
  background-color: #f1f5f9;
  color: #334155;
}

.action-button.secondary:hover {
  background-color: #e2e8f0;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .login-card {
    padding: 1.5rem;
  }
  
  .login-title {
    font-size: 1.25rem;
  }
}

.form-item label {
  font-size: 13px;
  color: #4b5563;
}

.form-item input {
  width: 100%;
  border-radius: 8px;
  border: 1px solid #d1d5db;
  padding: 8px 10px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-item input:focus {
  outline: none;
  border-color: #111827;
}

.login-button {
  margin-top: 4px;
  border-radius: 999px;
  border: none;
  padding: 8px 12px;
  font-size: 14px;
  font-weight: 500;
  color: #f9fafb;
  background: #111827;
  cursor: pointer;
}

.login-button:disabled {
  opacity: 0.6;
  cursor: default;
}

.login-error {
  margin-top: 10px;
  font-size: 13px;
  color: #b91c1c;
}
</style>
